/**
 * (c)Copyright 2008 SinoCredit Co,Ltd. All Rights Reserved.
 * GftUserServiceImpl.java, 1:29:46 PM
 * @author yipeng
 * @since Jan 9, 2008
 * @version 1.0
 * change list:
 * yipeng   (创建)
 */

package com.sys.service.impl;


import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.sys.base.UserBean;
import com.sys.base.service.BaseGftServiceImpl;
import com.sys.dao.model.GftRight;
import com.sys.dao.model.GftRole;
import com.sys.dao.model.GftRoleRight;
import com.sys.dao.model.GftUserInfo;
import com.sys.dao.model.GftUserRole;
import com.sys.plat.bean.PageBean;
import com.sys.service.GftUserService;
import com.sys.system.Constants;

public class GftUserServiceImpl extends BaseGftServiceImpl implements
        GftUserService {

    public UserBean login(String userName, String password) {
        UserBean userBean = null;
        String hql = "FROM GftUserInfo WHERE userName=? AND passWord=? AND status=?";
        List<GftUserInfo> userList = super.dao.listByHql(hql, userName, password, Constants.STATUS_YES);
        if (null != userList && 1 == userList.size()) {
            userBean = new UserBean();
            GftUserInfo user = userList.get(0);
            userBean.setGftUserInfo(user);
            userBean.setGftRightMap(this.getUserRightsMap(user.getId()));
        }
        return userBean;
    }

    /**
     * 获得gft用户权限
     *
     * @param id gft用户ID
     * @return 权限map{权限�??, 权限对象}
     */
    private Map<String, GftRight> getUserRightsMap(String id) {
        Map<String, GftRight> map = new HashMap<String, GftRight>();
        String hql = "FROM GftRight t,GftRole o,GftUserRole u,GftRoleRight r WHERE u.roleId=r.roleId AND r.rightId=t.id AND o.id=u.roleId AND o.status=? AND t.status=? AND u.userId=?";
        Iterator<Object[]> iter = super.dao.listByHql(hql,
                Constants.STATUS_YES, Constants.STATUS_YES, id).iterator();
        while (iter.hasNext()) {
            Object[] obj = iter.next();
            GftRight right = (GftRight) obj[0];
            map.put(right.getRightName(), right);
        }
        return map;
    }

    public GftUserInfo editUser(String id) {
        return (GftUserInfo) super.dao.getObject(GftUserInfo.class, id);
    }

    public List<GftRole> getRolesByUserId(String id) {
        List<GftRole> list = new ArrayList<GftRole>();
        String hql = "FROM GftUserRole u,GftRole r WHERE u.roleId=r.id AND u.userId=?";
        Iterator iter = super.dao.listByHql(hql, id).iterator();
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            list.add((GftRole) obj[1]);
        }
        return list;
    }

    public void addOrUpdateUser(GftUserInfo user) {
        if (null == user.getId() || "".equals(user.getId())) {
            addObject(user);
        } else {
            // 密码不为空时，修改密�??
            if (user.getPassWord() != null && !"".equals(user.getPassWord())) {
                updateObject(user);
            } else { // 更新用户其他信息
                List<GftUserInfo> userList = super.dao.listByHql("FROM GftUserInfo WHERE id=?", user.getId());
                if (userList != null && userList.size() > 0) {
                    GftUserInfo userOld = userList.get(0);
                    userOld.setStatus(user.getStatus());
                    userOld.setUserName(user.getUserName());
                    userOld.setUserType(user.getUserType());
                }
            }
        }
    }

    public void list(PageBean pageBean, String tableName) {
        pageBean.setHql("FROM " + tableName);
        this.page(pageBean);
    }

    public int deleteUser(String[] ids) {
        super.delObjectByColumn(ids, GftUserRole.class, "userId");
        return super.delObject(ids, GftUserInfo.class);
    }

    /*public void switchStatus(GftUserInfo user) {
        for (Object obj : this.dao.listByHql("FROM GftUserInfo WHERE id=?", user.getId())) {
            GftUserInfo role = (GftUserInfo) obj;
            String status = role.getStatus();
            if (Constants.STATUS_YES.equals(status))
                status = Constants.STATUS_NO;
            else if (Constants.STATUS_NO.equals(status))
                status = Constants.STATUS_YES;
            role.setStatus(status);
            updateObject(role);
        }
    }*/

    public GftRole editRole(String id) {
        return (GftRole) super.dao.getObject(GftRole.class, id);
    }

    public List<GftRight> getRightsByRoleId(String id) {
        List<GftRight> list = new ArrayList<GftRight>();
        String hql = "FROM GftRoleRight u,GftRight r WHERE u.rightId=r.id AND u.roleId=?";
        Iterator iter = this.dao.listByHql(hql, id).iterator();
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            list.add((GftRight) obj[1]);
        }
        return list;
    }

    public void addOrUpdate(Object obj) {
        try {
            String id = BeanUtils.getProperty(obj, "id");
            if (null != id && !"".equals(id))
                updateObject(obj);
            else
                addObject(obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private void addObject(Object object) {
        this.dao.saveObject(object);
    }

    private void updateObject(Object object) {
        this.dao.updateObject(object);
    }

    /*public void switchRoleStatus(GftRole role) {
        for (Object obj : this.dao.listByHql("FROM GftRole WHERE id=?", role.getId())) {
            GftRole rrole = (GftRole) obj;
            String status = rrole.getStatus();
            if (Constants.STATUS_YES.equals(status))
                status = Constants.STATUS_NO;
            else if (Constants.STATUS_NO.equals(status))
                status = Constants.STATUS_YES;
            rrole.setStatus(status);
            updateObject(rrole);
        }
    }*/

    public int deleteRole(String[] ids) {
        this.delObjectByColumn(ids, GftRoleRight.class, "roleId");
        return delObject(ids, GftRole.class);
    }

    public String getRightIdsByRoleId(String id) {
        StringBuffer buf = new StringBuffer();
        String hql = "FROM GftRoleRight u,GftRight r WHERE u.rightId=r.id AND u.roleId=?";
        Iterator iter = this.dao.listByHql(hql, id).iterator();
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            GftRight right = (GftRight) obj[1];
            buf.append(',').append(right.getId());
        }
        String rightIds = buf.toString();
        if (null != rightIds && !"".equals(rightIds))
            rightIds = rightIds.substring(1);
        return rightIds;
    }

    public void updateRoleRight(String id, String[] rightIdArray) {
        deleteById(id, 2);
        if (null != rightIdArray)
            addRoleRight(id, rightIdArray);
    }

    /**
     * 删除用户/角色的配置数�??
     *
     * @param id   用户ID/角色ID
     * @param type 1: 用户/2: 角色
     */
    private void deleteById(String id, int type) {
        String hql = "DELETE FROM GftUserRole WHERE userId=?";
        if (2 == type)
            hql = "DELETE FROM GftRoleRight WHERE roleId=?";
        List<String> list = new ArrayList<String>();
        list.add(id);
        this.dao.delete(hql, list);
    }

    private void addRoleRight(String roleId, String[] rightIdArray) {
        for (String rightId : rightIdArray) {
            GftRoleRight roleRight = new GftRoleRight();
            roleRight.setRoleId(roleId);
            roleRight.setRightId(rightId);
            addObject(roleRight);
        }
    }

    public int delRoleRight(String[] configId) {
        return super.delObjectByColumn(configId, GftRoleRight.class, "rightId");
    }

    public String getRoleIdsByUserId(String id) {
        StringBuffer buf = new StringBuffer();
        String hql = "FROM GftUserRole u,GftRole r WHERE u.roleId=r.id AND u.userId=?";
        Iterator iter = this.dao.listByHql(hql, id).iterator();
        while (iter.hasNext()) {
            Object[] obj = (Object[]) iter.next();
            GftRole role = (GftRole) obj[1];
            buf.append(',').append(role.getId());
        }
        String roleIds = buf.toString();
        if (null != roleIds && !"".equals(roleIds))
            roleIds = roleIds.substring(1);
        return roleIds;
    }

    public void updateUserRole(String id, String[] roleIdArray) {
        deleteById(id, 1);
        if (null != roleIdArray)
            addUserRole(id, roleIdArray);
    }

    private void addUserRole(String id, String[] roleIdArray) {
        for (String roleId : roleIdArray) {
            GftUserRole userRole = new GftUserRole();
            userRole.setUserId(id);
            userRole.setRoleId(roleId);
            addObject(userRole);
        }
    }

    public GftRight editRight(String id) {
        return (GftRight) super.dao.getObject(GftRight.class, id);
    }

    public int deleteRight(String[] ids) {
        return super.delObject(ids, GftRight.class);
    }

    public int delUserRole(String[] configId) {
        return super.delObjectByColumn(configId, GftUserRole.class, "roleId");
    }

    public void switchStatus(Object o, Class clazz) {
        try {
            String id = BeanUtils.getProperty(o, "id");
            log.debug("Class Name:\t" + (clazz.toString().split("\\s"))[1]); // 去除类名前的"class "
            for (Object obj : this.dao.listByHql("FROM " + (clazz.toString().split("\\s"))[1] + " WHERE id=?", id)) {
                String status = BeanUtils.getProperty(obj, "status");
                if (Constants.STATUS_YES.equals(status))
                    status = Constants.STATUS_NO;
                else if (Constants.STATUS_NO.equals(status))
                    status = Constants.STATUS_YES;
                BeanUtils.setProperty(obj, "status", status);
                updateObject(obj);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use FileTool | Settings | FileTool Templates.
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use FileTool | Settings | FileTool Templates.
        } catch (NoSuchMethodException e) {
            e.printStackTrace();  //To change body of catch statement use FileTool | Settings | FileTool Templates.
        }
    }

    public boolean checkObj(String tableName, String columnName, String columnValue) {
        StringBuffer buf = new StringBuffer();
        buf.append("FROM ").append(tableName).append(" WHERE ").append(columnName).append(" =?");
        List list = super.dao.listByHql(buf.toString(), columnValue);
        return null != list && !list.isEmpty();
    }
}